// my/pages/changePwd/changePwd.js
Page({
  data: {
    loginUserInfo:{},
    
    formData: {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    },
    errorMessage: '',
    loading: false
  },

  // 输入事件处理
  onInput(e) {
    const name = e.currentTarget.dataset.name;
    const value = e.detail.value;
    this.setData({
      [`formData.${name}`]: value
    });
  },

  // 提交修改密码
  submitChangePassword() {
    const { oldPassword, newPassword, confirmPassword } = this.data.formData;
    
    // 表单验证
    if (!oldPassword) {
      this.setData({ errorMessage: '请输入旧密码' });
      return;
    }
    
    if (!newPassword) {
      this.setData({ errorMessage: '请输入新密码' });
      return;
    }
    
    if (newPassword.length < 6) {
      this.setData({ errorMessage: '新密码长度至少6位' });
      return;
    }
    
    if (newPassword !== confirmPassword) {
      this.setData({ errorMessage: '两次输入的新密码不一致' });
      return;
    }
    
    // 获取存储的userId
    const userId = wx.getStorageSync('userId');

    if (!userId) {
      this.setData({ errorMessage: '用户未登录，请重新登录' });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }
    
    // 显示加载状态
    this.setData({ loading: true, errorMessage: '' });
    
    // 发送请求到后端
    wx.request({
      url: 'http://localhost:8080/user/pwd',
      method: 'POST',
      data: {
        id: userId,
        oldPwd: oldPassword,  
        newPwd: newPassword    
      },
      success: (res) => {
        this.setData({ loading: false });
        
        if (res.data.code === 200) {
          wx.showToast({
            title: '密码修改成功，即将重新登录',
            icon: 'success',
            duration: 3000,
            success: () => {
              // 修改成功后跳转到个人中心或登录页
              wx.clearStorageSync();
              const app = getApp()
              app.globalData.loginUserInfo = null
              wx.reLaunch({ url: '/pages/login/login' });
            }
          });
        } else {
          const errorMsg = res.data.message || '密码修改失败，请重试';
          this.setData({ errorMessage: errorMsg });
          
          // 如果是旧密码错误，3秒后自动清空旧密码输入框
          if (errorMsg.includes('旧密码')) {
            setTimeout(() => {
              this.setData({ 'formData.oldPassword': '' });
            }, 3000);
          }
        }
      },
      fail: (err) => {
        this.setData({ 
          errorMessage: '网络请求失败，请检查网络连接',
          loading: false 
        });
        console.error('修改密码请求失败:', err);
      }
    });
  },

  // 取消修改
  cancelChange() {
    wx.navigateBack({ delta: 1 });
  },

  // 生命周期函数：检查登录状态
  onLoad(options) {
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/login/login' });
          } else {
            wx.navigateBack({ delta: 1 });
          }
        }
      });
    }
  }
});